 /**
  * The simple seajs module, menu accordion plugin.
  * jquery depandancy jquery 1.9.1+ (on() event delegation)
  *
  */
 var $ = require("jquery");

 var Accordion = function(selector, opts) {
     // default configuration
     var defaults = {
         expandClass: "expanded",
         onlyExpandOne: false,
         expandSelector: "dd.sub",
         clickItemSelector: "dl dt i",
         // Required: the container of expandSelector and clickItemSelector
         itemBlockSelector: 'dl'
     };
     // override existed configuration
     var cfg = $.extend({}, defaults, opts);
     // save root selector
     this.$selector = $(selector);
     this.$itemBlocks = this.$selector.find(cfg.itemBlockSelector);

     this.$lastClickItem = null;
     this.$lastExpanedItem = null;

     //Main function deal accordion toggle animation
     var collapse = function($clickItem, $collapseItem) {

         if ($collapseItem.is(":visible")) {
             // remove toggle class. expandClass.
             $clickItem.removeClass(cfg.expandClass);
             $collapseItem.slideUp("fast");
         } else {
             $clickItem.addClass(cfg.expandClass);
             $collapseItem.slideDown("fast");
             this.$lastClickItem = $clickItem;
             this.$lastExpanedItem = $collapseItem;
         }
     };
     this.init = function() {
         // register event for click item.
         var self = this;
         this.$selector.on("click", cfg.clickItemSelector, function(event) {
             var $this = $(this);
             if (cfg.onlyExpandOne) {
                 // slideUp all expanded elements.
                 if (self.$lastExpanedItem) self.$lastExpanedItem.slideUp('fast');
                 if (self.$lastClickItem) self.$lastClickItem.removeClass(cfg.expandClass);
             }
             // collapse current child item.
             collapse.call(self, $this, $this.closest(cfg.itemBlockSelector).find(cfg.expandSelector));
         });
     };
 };
 // extend methods to it's prototype.
 Accordion.prototype.run = function() {
     // inital Accordion. 
     this.init();
 };
 module.exports = {
     accordion: function(selector, opts) {
         new Accordion(selector, opts).run();
     }
 };
